/**
 * 转发服务
 */
#ifndef __FORWARD_SERVICE_H_INCLUDED__
#define __FORWARD_SERVICE_H_INCLUDED__

// stl headers
#include <string>
#include <map>
using std::string;
using std::map;
using std::pair;

#include <pthread.h>
#include <netinet/in.h>
#include "common.h"
#include "forward_event.h"
#include "forward_session.h"
#include "forward_pair.h"
#include "forward_endpoint.h"
#include "forward_socket.h"
#include "epoll_monitor.h"
#include "mutex.h"

class forward_service{

public:

    forward_service(void);
    ~forward_service(void);

    static forward_service* get_instance();
    static void destroy();

    bool is_running();
    bool start_service(int port);
    bool stop_service();
    

    // 端信息函数
    forward_session* get_session(unsigned short src_port);
    void add_session(forward_session* sess);
    void remove_session(unsigned short src_port);
    forward_session* safe_get_session(unsigned short src_port);
    void safe_add_session(forward_session* sess);
    void safe_remove_session(unsigned short src_port);
	forward_pair safe_get_session_pair(unsigned short src_port);

private:

    static forward_service* instance;

    // 工作线程实现
    static void* work_thread(void* param);
    void work_thread_impl();

    void print_pair_map();

    void handle_tcp(const forward_event* cur_fwd_evt, int cur_io_evt);
    void handle_udp(const forward_event* cur_fwd_evt, int cur_io_evt);
    void handle_accept(int cur_fd);

	void recycle();

private:

    bool running;
    pthread_t tid;
    int forward_port_tcp;
    int forward_port_udp;

    // UDP转发句柄
    forward_socket tcp_srv;
    forward_socket udp_srv;

    // epoll文件描述符
    int epfd;

    // epoll监听
    epoll_monitor ep_monitor;

    // 转发地址对
    typedef map<unsigned short, forward_session*> session_map_t;
    typedef session_map_t::iterator session_map_iterator;
    session_map_t session_map;

    std::mutex pair_map_mutex;
};

#endif // __FORWARD_SERVICE_H_INCLUDED__
